<template>
  <div class="content">
    <div class="breadcrumb" :gutter="24">
      {{$t('model.model_config')}}{{modelName}}
    </div>
    <el-form ref="form" :model="formData" label-width="70px" size="small">
      <el-row :gutter="28">
        <el-col :xs="3" :sm="1" :md="1" :lg="1" :xl="1">
        </el-col>
        <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
          <el-form-item :label="$t('recipe.assignment_name')">
            <el-input v-model="formData.keyword" clearable placeholder=""></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
          <el-form-item label-width="0px">
            <el-button type="primary" size="small" @click="handleSearch">{{ $t("common.query") }}</el-button>
          </el-form-item>
        </el-col>

        <div class="btngroup">
          <el-button type="primary" size="small" @click="handleAdd()">{{ $t("model.sel_model") }}</el-button>
          <el-button type="primary" size="small" @click="saveFactor()">{{ $t("common.preservation") }}</el-button>
          <el-button type="primary" size="small" @click="handleAnalysis()">{{ $t("model.analysis") }}</el-button>
        </div>
      </el-row>
    </el-form>
    <div class="dataContent">
      <tableList :tableData="tableData" :pager="pager" v-if="!isCard" :tableLoading="tableLoading" @handleEdit="handleEdit"
        @sortChange="sortChange"></tableList>
      <div class="pagination-area">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[20, 30, 50, 100]"
          :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowDialog" :close-on-click-modal="false" width="60vh" class="isShowDialog"
      :before-close="handleClose">
      <el-form :model="ruleForm" label-width="80px" ref="ruleForm" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item :label="$t('model.model_name')" prop="woId">
              <el-select v-model="ruleForm.modelName" remote filterable :remote-method="remoteMethod" placeholder="" clearable
                @change="changeRecipeId">
                <el-option v-for="(item,index) in formulaList" :key="index" :label="item.modelName" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('recipe.formula_name')" prop="recipeId">
              <el-input disabled v-model="ruleForm.recipeName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24">
            <el-form-item :label="$t('recipe.material_code')" prop="item">
              <el-input disabled v-model="ruleForm.item" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('dialog.numbers')" prop="itemQty">
              <el-input disabled v-model="ruleForm.itemQty" placeholder="" min="0" v-enterNumber2 type="number" clearable>
                <template slot="append">{{ruleForm.uomId}}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleAddFormula('ruleForm')"
          :loading="loading">{{ $t("common.determine") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { modeling } from "@/api/model"
import { scheduling } from "@/api/scheduling"
import tableList from "./template/tableList.vue"
export default {
  components: {
    tableList,
  },
  data () {
    let woIdFn = (rule, value, callback) => {
      if (this.title == "新增" && value) {
        scheduling.workOrderCheck({ woId: value }).then(res => {
          console.log(res)
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error('模型名称不能重复'));
          }
        }).catch(e => {
          callback(new Error('模型名称不能重复'));
        })
      } else if (!value) {
        callback(new Error('模型名称不能为空'));
      } else {
        callback();
      }
    }
    let lotNumFn = (rule, value, callback) => {
      if (this.title == "新增" && value) {
        scheduling.checkLot({ lotNum: value }).then(res => {
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error('批次号已存在'));
          }
        })
      } else if (this.title == "编辑" && value) {
        scheduling.checkLot({ lotNum: value, woId: this.ruleForm.woId }).then(res => {
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error('批次号已存在'));
          }
        })
      }
    }
    return {
      formData: {
        keyword: "",
        time: [],
        status: ['0', '1', '2', '4']
      },
      ruleForm: {
        recipeId: "",
        recipeName: '',
        modelName: "",
        itemQty: "",
        uomId: "",
        creator: '',
      },
      pager: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        field: 'createTime',
        order: 'DESC',
      },
      formulaPage: {
        pageNum: 1,
        pageSize: 20,
      },
      keyword: "",
      formulaList: [],
      tableData: [],
      icon: "icon-biaoge",
      isShowDialog: false,
      loading: false,
      selectLoading: false,
      tableLoading: false,
      title: this.$t('model.sel_model'),
      rules: {
        recipeId: [{ required: true, message: '配方名称不能为空', trigger: 'change' }],
        modelName: [
          { required: true, message: '模型名称不能为空', trigger: 'blur' },
        ],
      },
      secle: "",
      isCard: false,
      disabled: -1,
      statusList: [
        {
          label: this.$t('workorder.newly_build'),
          value: "0"
        }, {
          label: this.$t('workorder.release'),
          value: "1"
        }, {
          label: this.$t('workorder.function'),
          value: "2"
        }, {
          label: "生产结束",
          value: "3"
        }, {
          label: this.$t('workorder.suspend'),
          value: "4"
        }, {
          label: this.$t('common.abandoned'),
          value: "5"
        }, {
          label: this.$t('common.examine'),
          value: "7"
        }, {
          label: this.$t('common.approval'),
          value: "8"
        }, {
          label: this.$t('common.refuse'),
          value: "9"
        }],
      echartsLoading: false,
      currObj: {},
      sysUserVosList: [],
      modelName: '',
    }
  },
  created () {
    this.getTbrecipeList()
  },
  methods: {
    //获取配方名称列表
    getTbrecipeList () {
      const param = {
        page: 1,
        size: 999,
      }
      modeling.modelProjectList(param).then(res => {
        if (res.code == 200) {
          this.formulaList = res.data.rows
        }
      })
    },
    factorList () {
      if (this.ruleForm.recipeId == '') {
        this.$message.error('请选择模型后查询');
        return
      }
      this.tableLoading = true
      let proId = this.formulaList.filter(ii => ii.fid == this.ruleForm.modelName)[0].fid
      const param = {
        jobDesc: this.formData.keyword,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        projectId: proId,
        field: 'jobDesc,stepId,phaseDesc',
        order: 'asc'
      }
      modeling.getFactorList(param).then(res => {
        this.tableLoading = false
        this.isShowDialog = false
        if (res.code == 200) {
          this.tableData = res.data.rows
          this.pager.total = res.data.total
        }
      }).catch(e => {
        this.tableLoading = false
      })
    },
    handleAnalysis () {
      this.tableLoading = true
      let proId = this.formulaList.filter(ii => ii.fid == this.ruleForm.modelName)[0].fid
      const param = {
        projectId: proId,
      }
      modeling.toAnalysis(param).then(res => {
        let resStr = JSON.stringify(res)
        this.tableLoading = false
        if (resStr.indexOf('成功') > -1) {
          this.$message.success('分析完成')
        } else {
          this.$message.warning('分析失败')
        }
      })
      // setTimeout(() => {
      //   this.tableLoading = false
      //   this.$message.success('分析完成')
      // }, 3000)
    },
    sortChange (column) {
      if (column.order === 'descending') {
        this.pager.field = column.prop
        this.pager.order = 'DESC'
      } else {
        this.pager.field = column.prop
        this.pager.order = 'ASC'
      }
      this.pager.pageNum = 1
      this.factorList()
    },
    handleSearch () {
      this.pager.pageNum = 1
      this.factorList()
    },
    //远程搜索配方名称
    remoteMethod (keyword) {
      this.keyword = keyword.trim();
      this.formulaPage.pageNum = 1
      setTimeout(() => {
        this.formulaList = []
        this.getTbrecipeList()
      }, 200)
    },
    handleAdd () {
      this.title = this.$t('model.sel_model')
      this.ruleForm = {}
      try {
        this.$refs['ruleForm'].resetFields();
      } catch (e) { }

      this.isShowDialog = true
    },
    handleEdit (row) {
      // this.secle = row.radioId
      // this.disabled = row.row.stateCd
      // this.currObj = row.row
      // console.log(row.row)
    },
    handleSizeChange (val) {
      this.pager.pageNum = 1
      this.pager.pageSize = val
      this.factorList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.factorList()
    },
    handleAddFormula (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.modelName = '->' + this.formulaList.filter(ii => ii.fid == this.ruleForm.modelName)[0].modelName

          let param = Object.assign({}, this.ruleForm)
          param.tbRecipeVo = {
            fid: ""
          }
          this.factorList()

        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },

    saveFactor () {
      this.tableLoading = true
      modeling.modifyFactorList(this.tableData).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.$message.success('保存成功');
        }
      }).catch(e => {
        this.tableLoading = false
      })
    },
    handleClose () {
      this.isShowDialog = false
    },
    changeRecipeId (val) {
      let item = this.formulaList.find(item => item.fid == val)

      this.ruleForm.recipeName = item.tbRecipe.recipeName

      this.ruleForm.recipeId = item.tbRecipe.fid
      this.ruleForm.itemQty = item.tbRecipe.itemQty
      this.ruleForm.item = item.item
      this.ruleForm.uomId = item.tbRecipe.uomId
      this.ruleForm.type = item.recipeStatus == 3 ? '1' : item.recipeStatus == 6 ? '2' : ''
    },

  }
}
</script>

<style scoped>
.btngroup {
  float: right;
  margin-right: 20px;
}
.change >>> .iconfont {
  font-size: 13px !important;
}
.pagination-area {
  text-align: right;
  padding-top: 20px;
  padding-bottom: 10px;
}
.isShowDialog >>> .el-select,
.isShowDialog >>> .el-date-editor {
  width: 100%;
}
.isShowDialog >>> .el-date-editor .el-range-separator {
  width: 8%;
}
.titmepicker >>> .el-date-editor {
  width: 100%;
}
.titmepicker >>> .el-date-editor .el-range-separator {
  width: 8%;
}
@media only screen and (max-width: 768px) {
  .titmepicker {
    display: none;
  }
}
.dataContent {
  /* height: calc(100vh - 180px); */
  border: 1px solid #ebeef5;
  overflow: auto;
}
.marginLing >>> .el-row {
  margin-left: 0px !important;
  margin-right: 0px !important;
}
</style>